package com.koron.operation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.koron.bean.base.Response;
import com.koron.common.core.business.configsettings.bean.ConfigDetailQuery;
import com.koron.common.core.business.configsettings.mapper.ConfigTypeMapper;
import com.koron.common.core.util.CodeTools;
import com.koron.operation.dispatch.bean.TabPmpMonitor;
import com.koron.operation.dispatch.bean.UnitRelationDo;
import com.koron.operation.dispatch.bean.dto.UnitSynDto;
import com.koron.operation.dispatch.enums.EquipmentEnum;
import com.koron.operation.dispatch.feign.MonitorFeign;
import com.koron.operation.dispatch.mapper.EquipmentDeMapper;
import com.koron.operation.dispatch.service.EquipmentRunService;
import com.koron.operation.startlog.bean.StartLogBean;
import com.koron.operation.startlog.services.StartLogService;
import com.koron.operation.util.StarLogUntil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Order(2)
@Component
public class OperationListener implements ApplicationRunner {

//    private final static String TASKID = "STARTLOG123456";//xxjob需要一个id标识，进行启动定时任务，这里业务可以固定好
//
//    @Autowired
//    private XxlJobService xxlJobService;

    @Autowired
    private EquipmentRunService equipmentrunservice;

    @Autowired
    private MonitorFeign monitorfeign;

    @Autowired
    private StartLogService startlogservice;

    @Override
    public void run(ApplicationArguments args) {

//        CronTask cronTask = xxlJobService.getCronTaskById(TASKID);
//        String jobName = "系统5分钟抓一次最新的开关机日志[" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm") + "]";
//        if(cronTask != null) {
//            xxlJobService.pause(TASKID);    //停止任务
//            xxlJobService.remove(TASKID);   //移除任务
//            // 新增任务
//            xxlJobService.addSimpleJob(TASKID, "0 0/5 * ? * * *", "water_02", jobName, "admin", "synStartLog", 120);
//        }
//        xxlJobService.start(TASKID);//启动任务

    }



    @XxlJob(value = "synStartLog")
    public void synStartLog() {
        String taskParam = XxlJobHelper.getJobParam();
        log.info("开停机日志同步任务启动成功:"+taskParam);
        List<String> paramlist = StrUtil.split(taskParam, ",");
        if (CollUtil.isEmpty(paramlist)) {
            return;
        }
        //系统库
        List<UnitRelationDo> unitrelist = ADOConnection.runTask(factory -> {
            ConfigTypeMapper configTypeMapper = factory.getMapper(ConfigTypeMapper.class);
            EquipmentDeMapper equipmentdemapper = factory.getMapper(EquipmentDeMapper.class);
            // 获取配置项id
            String detailId = configTypeMapper.getByClassifyCodeAndCode("operation", "unit_relation").getId();
            // 根据配置id 和 租户appid 查出 机组对应关系
//            ConfigDetailQuery configDetailQuery = new ConfigDetailQuery(detailId, "8e7e09b125ea4dbc8d0515564ceda01d");
            ConfigDetailQuery configDetailQuery = new ConfigDetailQuery(detailId, paramlist.get(1));
            // 所有泵张机组
            return equipmentdemapper.getUnitrelationlist(configDetailQuery);
        }, List.class);

//        List<UnitSynDto> unitSynFilterlist = ADOConnection.runTask("water_02", equipmentrunservice, "getUnitStartLogParameter", List.class, unitrelist);
        List<UnitSynDto> unitSynFilterlist = ADOConnection.runTask(paramlist.get(2), equipmentrunservice, "getUnitStartLogParameter", List.class, unitrelist);

        //获取所有泵张的开停机记录
        Response<List<UnitSynDto>> responseMsg = monitorfeign.getUnitStartLog(unitSynFilterlist);
        Assert.isFalse(responseMsg.getCode() != 200, responseMsg.getDescription());
        if (responseMsg.getCode() == 200) {
            List<UnitSynDto> unitloglist = responseMsg.getData();//开停机记录
            List<StartLogBean> insertlist = new ArrayList();     //开关机插库模式
            //遍历不同泵站
            unitloglist.stream().forEach(a -> {
                if (CollUtil.isNotEmpty(a.getRecordlist())) {
                    List<TabPmpMonitor> distinct = a.getRecordlist().stream().distinct().collect(Collectors.toList());//去重
                    //遍历泵站下的同步数据
                    distinct.stream().forEach(di -> {
                        StartLogBean bean = new StartLogBean();
                        bean.setId(CodeTools.getCode32());
                        bean.setDeptManage(a.getDeptManage());
                        bean.setDeptManageName(a.getDeptManageName());
                        bean.setEquipmentId(a.getEquipmentId());
                        bean.setEquipmentName(a.getEquipmentName());
                        bean.setEquipmentType(EquipmentEnum.UNIT.getValue());
                        bean.setOperateTime(DateUtil.parse(di.getLastsyntime()));//同步时间
                        bean.setOperateType(StarLogUntil.ConverOperType(di.getOper()));//转换成eam类型
                        bean.setContent(di.getDescription());//原因
                        bean.setDataSource(StrUtil.format("{}-{}", "syn", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
                        bean.setIsConfirm(0);//同步过来的数据都是未确认的
                        insertlist.add(bean);
                    });
                }
            });
            ADOConnection.runTask(paramlist.get(2), startlogservice, "bathInsert", Void.class, insertlist);
            log.info("开停机日志同步任务执行结束:"+taskParam);
        }

        return;
    }



}
